<template>
    <!-- 预处理算法开发与管理 -->
    <div class="model-manage">
        <div class="mm-panel-wrapper-left">
            <Tree ref="leftTreeRef" :isOwnAccount="true" :topAdd="true" :topAddMenu="right_menuList.rightMenuList_1"
                :folderMenu="right_menuList.rightMenuList_3" :secondMenu="right_menuList.rightMenuList_3_2"
                :fileMenu="right_menuList.rightMenuList_4" :treeData="ownTreeData" :currentNodeKey="currentNodeKey"
                :defaultExpandedKeys="defaultExpandedKeys" @handleAddNode="handleAddModel"
                @addOrUpdateFolder="handleAddOrUpdateFolder" @nodeClick="nodeClick" @nodeDelete="handleNodeDelete"
                @moveNodeOrder="moveNodeOrder" @handleMenuClick="handleMenuClick">
            </Tree>
        </div>
        <div class="mm-divider"></div>
        <div class="mm-panel-wrapper-right">
            <div class="padding20">
                <!-- 算法 -->
                <div v-if="isFolder">
                    <div class="mm-panel-title mb-10">
                        算法基本信息
                        <el-button style="float: right;" class="ml-10" type="primary" @click="handleSave">保存</el-button>
                    </div>
                    <el-form ref="folderForm" :model="folderForm" :rules="folderRules" label-width="150px">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="名称" prop="name">
                                    <el-input v-model="folderForm.name"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="创建日期" prop="createTime">
                                    <el-date-picker v-model="folderForm.createTime" type="date" placeholder="选择日期">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="描述" prop="description">
                            <el-input type="textarea" v-model="folderForm.description"></el-input>
                        </el-form-item>
                    </el-form>
                </div>
                <!-- 算法版本 -->
                <div v-else>
                    <div class="mm-panel-title mb-10">
                        算法基本信息
                        <el-button style="float: right;" class="ml-10" type="primary" @click="handleSave">保存</el-button>
                    </div>
                    <el-form ref="itemForm" :model="itemForm" :rules="rules" label-width="150px">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="名称" prop="name">
                                    <el-input v-model="itemForm.name"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="版本号" prop="versionName">
                                    <el-input v-model="itemForm.versionName"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="创建日期" prop="createTime">
                                    <el-date-picker v-model="itemForm.createTime" type="date" placeholder="选择日期">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="基准版本" prop="baseVersionName">
                                    <div class="flex">
                                        <!-- <el-input v-model="itemForm.baseVersionName"></el-input> -->
                                        <el-select v-model="itemForm.baseId">
                                            <el-option v-for="(item, index) in baseVersionList" :label="item.name"
                                                :value="item.id" :key="'baseVersionList' + index"></el-option>
                                        </el-select>
                                        <!-- <el-button type="primary" @click="handleSave">选择</el-button> -->
                                    </div>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="描述" prop="description">
                            <el-input type="textarea" v-model="itemForm.description"></el-input>
                        </el-form-item>
                        <el-form-item label="镜像选择" prop="imageId">
                            <div class="flex">
                                <el-input v-model="itemForm.imageName" :readonly="true"></el-input>
                                <el-button type="primary" @click="openImage">选择</el-button>
                            </div>
                        </el-form-item>
                        <el-form-item label="输入样本集选择" prop="inputSampleId">
                            <div class="flex">
                                <el-select v-model="itemForm.inputSampleId">
                                    <el-option v-for="(item, index) in inputSampleList" :label="item.name"
                                        :value="item.id" :key="'inputSampleList' + index"></el-option>
                                </el-select>
                                <!-- <el-button type="primary" @click="handleSave">选择</el-button> -->
                            </div>
                        </el-form-item>
                        <el-form-item label="输出样本集选择" prop="outputSampleId">
                            <div class="flex">
                                <el-select v-model="itemForm.outputSampleId">
                                    <el-option v-for="(item, index) in outSampleList" :label="item.name"
                                        :value="item.id" :key="'outSampleList' + index"></el-option>
                                </el-select>
                                <!-- <el-button type="primary" @click="handleSave">选择</el-button> -->
                            </div>
                        </el-form-item>
                    </el-form>
                    <div class="mm-panel-title mb-10">
                        算法开发环境状态信息
                        <el-button style="float: right;margin-left: 10px;" class="ml-10" type="primary"
                            @click="handSuanZi">算子构建</el-button>
                        <el-button style="float: right;" class="ml-10" type="primary"
                            @click="handleOnline">在线开发</el-button>
                        <el-button v-show="itemForm.runState == 0" style="float: right;margin-left: 10px;" class="ml-10"
                            type="primary" @click="handleOpen">开发容器启动</el-button>
                        <el-button v-show="itemForm.runState != 0" style="float: right;margin-left: 10px;" class="ml-10"
                            type="primary" @click="handleClose">开发容器停止</el-button>

                    </div>
                    <div style="border: 1px solid var(--ui-border-color-split);">
                        <div style="padding: 20px;text-align: center;">
                            <!-- 0=未完成构建 1=完成构建 2=构建失败 -->
                            构建状态: {{ itemForm.buildState == 0 ? '未完成构建' : itemForm.buildState == 1 ? '完成构建' :
                                itemForm.buildState
                                    == 2 ? '构建失败' : '未完成构建' }}
                        </div>
                        <div style="padding: 20px;text-align: center;">
                            <!-- 0=未运行 1=启动中 2=运行中 3=错误 -->
                            运行状态: {{ itemForm.runState == 1 ? '启动中' : itemForm.runState == 2 ? '运行中' : itemForm.runState
                                == 3 ? '错误' : '未运行' }}
                        </div>
                        <div style="padding: 20px;text-align: center;display: flex;">
                            <div style="width: 50%;">
                                CPU: {{ podResourceUsage.cpuUsagePercent }} %

                                <el-progress type="circle" :percentage="podResourceUsage.cpuUsagePercent"></el-progress>
                            </div>
                            <div style="width: 50%;">
                                内存: {{ podResourceUsage.memoryUsagePercent }} %
                                <el-progress type="circle"
                                    :percentage="podResourceUsage.memoryUsagePercent"></el-progress>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <el-dialog title="镜像选择" :visible.sync="imageDialog" width="400px" append-to-body>
            <div style="width:100%;height: 500px;overflow: auto;">
                <el-tree :data="imageData" highlight-current :props="{
                    children: 'children',
                    label: 'name'
                }" @node-click="imageNodeClick"></el-tree>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="chooseImage">确 定</el-button>
                <el-button @click="imageDialog = false">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog title="算子构建" :visible.sync="openSuanZi" width="1200px" append-to-body>
            <div style="width:100%;height: 500px;overflow: auto;display: flex;">
                <div style="width: 50%;padding: 0 20px;">
                    <el-form :model="itemForm" label-width="120px">
                        <el-form-item label="启动命令" prop="startupCommand">
                            <el-input v-model="itemForm.startupCommand"></el-input>
                        </el-form-item>
                    </el-form>
                    <div class="mm-panel-title mb-10">
                        环境变量列表
                        <el-button style="float: right;" class="ml-10" type="primary"
                            @click="envVariableListAdd">添加</el-button>
                    </div>
                    <el-table v-loading="loading" :data="itemForm.envVariableList">
                        <el-table-column label="序号" type="index" width="50" align="center">
                        </el-table-column>
                        <el-table-column label="变量名" align="center" prop="name" :show-overflow-tooltip="true">
                            <template slot-scope="scope">
                                <el-input v-model="scope.row.name"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="变量值" align="center" prop="value" :show-overflow-tooltip="true">
                            <template slot-scope="scope">
                                <el-input v-model="scope.row.value"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button type="danger" @click="envVariableListDel(scope.row.$index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div style="width: 50%;padding: 0 20px;">
                    <div class="mm-panel-title mb-10">
                        启动参数
                        <el-popover title="提示" width="600" trigger="hover" content="" placement="left">
                            <pre style="text-align:left;">
                                {
                                "group1":{ # 参数分组，仅做web显示使用
                                "--attr1":{ # 参数名
                                "type":"str", # str,text,json,int,float,bool,list
                                "item_type": "str", # 在type为text，item_type可为python，java，json，sql
                                "label":"参数1", # 中文名
                                "require":1, # 是否必须
                                "choice":[], # 设定输入的可选值，可选值
                                "range":"", # int和float型时设置最小最大值,"min,max"
                                "default":"", # 默认值
                                "placeholder":"", # 输入提示内容
                                "describe":"这里是这个参数的描述和备注",
                                "editable":1 # 是否可修改
                                },
                                "--attr2":{
                                ...
                                }
                                },
                                "group2":{
                                }
                                }
                            </pre>
                            <div slot="reference" style="float: right;">
                                <i class="el-icon-question"></i>
                            </div>
                        </el-popover>
                    </div>
                    <!-- height: calc(100% - 30px); -->
                    <div style="border: 1px solid var(--ui-border-color-split);background-color: var(--app-nav-bg);">
                        <el-input type="textarea" :rows="21" placeholder="请输入json" v-model="itemForm.startupParam">
                        </el-input>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleSave">确 定</el-button>
                <el-button @click="openSuanZi = false">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog title="新增" :visible.sync="openDialog" width="800px" append-to-body>
            <div>
                <!-- 在此处添加弹窗内容 -->
                <p>这里是新增弹窗的内容区域</p>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary">确 定</el-button>
                <el-button @click="openDialog = false">取 消</el-button>
            </div>
        </el-dialog>
        <AddOrUpdateFolder v-if="isAddOrUpdateFolder" :preSetType="2" ref="addOrUpdateFolderRef" @refresh="getList">
        </AddOrUpdateFolder>
        <AddOrUpdateModel v-if="isAddOrUpdateModel" :preSetType="2" ref="addOrUpdateModelRef" @refresh="getList">
        </AddOrUpdateModel>
    </div>
</template>

<script>
import { mapState } from "vuex";
import Tree from "@/components/LeftTree/tree.vue";
import AddOrUpdateModel from "./components/add-or-update-model.vue";
import AddOrUpdateFolder from "./components/add-or-update-folder.vue";
import {
    getTreeApi,
    deleteTreeApi,
    moveTreeApi,
    getAlgorithmDetailsApi,
    startAlgorithApi,
    closeAlgorithApi,
    getOnlineAddress,
    updateTreeApi,
    getSampleDecisionListByType,
    updateAlgorithmManageApi,
    getBaseVersionList,
    getPodResourceUsage
} from "@/api/myspace/preprocessing/index";
export default {
    data() {
        return {
            podResourceUsage: {},//资源占用情况
            inputSampleList: [],
            outSampleList: [],
            baseVersionList: [],
            currentImage: {},
            imageDialog: false,
            imageData: [],
            openSuanZi: false,
            folderRules: {
                name: [{ required: true, message: "名称不可为空", trigger: "blur" }],
            },
            rules: {
                name: [{ required: true, message: "名称不可为空", trigger: "blur" }],
                versionName: [{ required: true, message: "版本号不可为空", trigger: "blur" }],
                createTime: [{ required: true, message: "创建时间不可为空", trigger: "blur" }],
                imageId: [{ required: true, message: "镜像不可为空", trigger: "blur" }],
                inputSampleId: [{ required: true, message: "输入样本集不可为空", trigger: "blur" }],
                outputSampleId: [{ required: true, message: "输出样本集不可为空", trigger: "blur" }],
            },
            folderForm: {
                name: "", //名称
                createTime: "",
                description: "", //描述
            },
            itemForm: {
                "createTime": "",
                "name": '',
                "versionName": "",
                "description": "",
                "imageId": '',
                "imageName": "",
                "inputSampleId": '',
                "outputSampleId": '',
                "runState": 0,
                "buildState": 0,
                "preSetId": 1,
                "envVariableList": [],
                startupParam: {
                    "group1": {//参数分组，仅展示使用
                        "attr1": {//参数名
                            "type": "str",//参数类型 str text json int float bool list
                            "item_type": "str",//type为text时，item_type可为 python java json sql
                            "label": "string参数",//中文名
                            "require": 1,//是否必填
                            "choice": [],//设定输入的可选值 有数据时使用下拉框，没数据时用输入框
                            "range": "",//int float时，设置最小值最大值 min,max
                            "default": "",//默认值
                            "placeholder": "请输入参数1",//提示信息
                            "describle": "参数1的描述",//描述或备注
                            "editable": 1//是否可修改 0-不可修改 1-可修改
                        },
                        "attr2": {
                            "type": "int",
                            "item_type": "str",
                            "label": "int类型参数",
                            "require": 1,
                            "choice": [],
                            "range": "0, 1",
                            "default": 1,
                            "placeholder": "请输入参数2",
                            "describle": "参数2的描述",
                            "editable": 0
                        },
                        "attr3": {
                            "type": "bool",
                            "item_type": "str",
                            "label": "bool类型参数",
                            "require": 1,
                            "choice": [true, false],
                            "range": "",
                            "default": true,
                            "placeholder": "请输入参数3",
                            "describle": "参数3的描述",
                            "editable": 1
                        }
                    },
                    "group2": {
                        "attr21": {
                            "type": "text",
                            "item_type": "python",
                            "label": "参数21",
                            "require": 1,
                            "choice": [],
                            "range": "",
                            "default": "",
                            "placeholder": "请输入参数21",
                            "describle": "参数21的描述",
                            "editable": 1
                        }
                    }
                }
            },
            openDialog: false,
            loading: false,
            tableList: [
                {
                    name: "xxxxx",
                    state: "运行中",
                    occupancy: "CPU:1/2 内存:1/2",
                    description: "针对xxx生成的样本数据",
                    createTime: "2021-01-01 10:10:10",
                },
                {
                    name: "xxxxx",
                    state: "运行中",
                    occupancy: "CPU:1/2 内存:1/2",
                    description: "针对xxx生成的样本数据",
                    createTime: "2021-01-01 10:10:10",
                },
                {
                    name: "xxxxx",
                    state: "运行中",
                    occupancy: "CPU:1/2 内存:1/2",
                    description: "针对xxx生成的样本数据",
                    createTime: "2021-01-01 10:10:10",
                },
                {
                    name: "xxxxx",
                    state: "运行中",
                    occupancy: "CPU:1/2 内存:1/2",
                    description: "针对xxx生成的样本数据",
                    createTime: "2021-01-01 10:10:10",
                },
                {
                    name: "xxxxx",
                    state: "运行中",
                    occupancy: "CPU:1/2 内存:1/2",
                    description: "针对xxx生成的样本数据",
                    createTime: "2021-01-01 10:10:10",
                },
                {
                    name: "xxxxx",
                    state: "运行中",
                    occupancy: "CPU:1/2 内存:1/2",
                    description: "针对xxx生成的样本数据",
                    createTime: "2021-01-01 10:10:10",
                },
                {
                    name: "xxxxx",
                    state: "运行中",
                    occupancy: "CPU:1/2 内存:1/2",
                    description: "针对xxx生成的样本数据",
                    createTime: "2021-01-01 10:10:10",
                },
            ],
            queryParams: { // 查询参数
                pageNum: 1,
                pageSize: 10,
                name: "",
                modelId: "",
                folderId: "",
            },
            isAddOrUpdateModel: false, // 是否打开新增数据模型弹框
            isAddOrUpdateFolder: false, // 是否打开创建目录的弹框
            isFolder: false, // 是否展示文件夹详情
            isFile: false, // 是否展示文件详情
            isModel: false, //是否是模型详情
            isModelGroupDetail: false, // 是否展示模型组详情,
            selectedNodeInfo: {}, // 当前选中节点的信息
            ownTreeData: [], // 本账户模型列表
            currentNodeKey: 0, // 当前选中节点的key
            defaultExpandedKeys: [] // 默认展开的节点
        };
    },
    components: {
        Tree,
        AddOrUpdateModel,
        AddOrUpdateFolder,
    },
    computed: {
        ...mapState({
            right_menuList: (state) => state.modelManageTool.right_menuList,
            selectedNodeId: (state) => state.modelManageTool.model.selectedNodeId,
            expandedNodeIds: (state) => state.modelManageTool.model.expandedNodeIds,
        }),
    },
    async created() {
        await this.getList();
        this.currentNodeKey = this.selectedNodeId;
        this.defaultExpandedKeys = this.expandedNodeIds;
        this.$nextTick(() => {
            this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
        })
        getSampleDecisionListByType({ decisionType: 1 }).then((res) => {
            if (res.code == 200) {
                this.inputSampleList = res.data;
            }
        });
        getSampleDecisionListByType({ decisionType: 2 }).then((res) => {
            if (res.code == 200) {
                this.outSampleList = res.data;
            }
        });
    },
    mounted() {

    },
    methods: {
        envVariableListAdd() {
            this.itemForm.envVariableList.push({
                name: '',
                value: ''
            })
        },
        envVariableListDel(index) {
            this.itemForm.envVariableList.splice(index, 1)
        },
        getDetail() {
            getAlgorithmDetailsApi(this.itemForm.id).then((response) => {
                if (response.code == 200) {
                    this.itemForm = response.data;
                    if (!this.itemForm.startupParam) {
                        this.itemForm.startupParam = "{\n    \"参数分组1\": {\n        \"--attr1\": {\n            \"type\": \"str\",\n            \"label\": \"参数1\",\n            \"default\": \"value1\",\n            \"editable\": 1,\n            \"describe\": \"这里是这个参数的描述和备注\"\n        }\n    }\n}"
                    }
                }
            })
        },
        async openImage() {
            const res = await getTreeApi({ preSetType: 1 });
            if (res.code == 200 && Array.isArray(res.data)) {
                this.imageData = res.data.length > 0 ? res.data[0].commonTreeList : [];
                this.currentImage = {}
                this.imageDialog = true;
            }
        },
        imageNodeClick(node) {
            this.currentImage = node;
        },
        chooseImage() {
            if (this.currentImage && this.currentImage.data.nodeType == 1) {
                this.itemForm.imageId = this.currentImage.data.refId;
                this.itemForm.imageName = this.currentImage.data.name;
                this.imageDialog = false;
                this.currentImage = {}
            } else {
                this.$message.error("请选择镜像")
            }
        },
        // 开启
        handleOpen() {
            startAlgorithApi(this.itemForm.id).then((res) => {
                this.$message.success("开启成功");
                this.getDetail()
            });
        },
        // 关闭
        handleClose() {
            closeAlgorithApi(this.itemForm.id).then((res) => {
                this.$message.success("关闭成功");
                this.getDetail()
            });
        },
        // 在线构建
        handleOnline() {
            getOnlineAddress(this.itemForm.id).then((res) => {
                // window.open(res.msg, '_blank');
                const iframeSrc = res.msg;
                // 生成唯一标识符
                const paramId = 'param_' + new Date().getTime();

                // 将参数存储到 sessionStorage
                sessionStorage.setItem(paramId, iframeSrc);

                // 在 URL 中传递标识符
                window.open(`/notebook/jupyter?paramId=${paramId}`, '_blank');
            });
        },
        //算子构建
        handSuanZi() {
            this.openSuanZi = true;
        },
        // 保存
        handleSave() {
            if (!this.folderForm.id && !this.itemForm.id) {
                return
            }

            if (this.isFolder) {
                // 校验文件夹表单
                this.$refs.folderForm.validate((valid) => {
                    if (valid) {
                        updateTreeApi(this.folderForm).then((res) => {
                            this.$message.success("保存成功");
                            // 重置校验状态
                            this.$refs.folderForm.clearValidate();
                        }).catch(() => {
                            // 保存失败时也重置校验状态（可选）
                            this.$refs.folderForm.clearValidate();
                        });
                    } else {
                        this.$message.warning("请填写必填项");
                        return false;
                    }
                });
            } else {
                // 校验文件表单
                this.$refs.itemForm.validate((valid) => {
                    if (valid) {
                        this.itemForm.buildState = 1
                        updateAlgorithmManageApi(this.itemForm).then((res) => {
                            this.$message.success("保存成功");
                            // 重置校验状态
                            this.$refs.itemForm.clearValidate();
                            this.getDetail()
                            this.openSuanZi = false
                        }).catch(() => {
                            // 保存失败时也重置校验状态（可选）
                            this.$refs.itemForm.clearValidate();
                        });
                    } else {
                        this.$message.warning("请填写必填项");
                        return false;
                    }
                });
            }
        },
        handleDevelopment() {
            const iframeSrc = 'http://192.168.1.109:3000/#/home/project';
            // 生成唯一标识符
            const paramId = 'param_' + new Date().getTime();

            // 将参数存储到 sessionStorage
            sessionStorage.setItem(paramId, iframeSrc);

            // 在 URL 中传递标识符
            window.open(`/notebook/jupyter?paramId=${paramId}`, '_blank');
        },
        handleEdit() {

        },
        handleCommand(command) {
            this.$message('click on item ' + command);
            switch (command) {
                case 'edit':
                    this.handleEdit();
                    break;
                case 'development':
                    this.handleDevelopment();
                    break;
            }
        },
        //新增
        handleAdd() {
            this.openDialog = true;
        },
        //查询
        handleQuery() {

        },
        //重置搜索条件
        resetQuery() {

        },
        async getList(newNodeId) {
            //预处理类型 1=镜像管理，2=在线开发运行，3=算子管理，4=任务流管理
            const params = { preSetType: 2 };
            const res = await getTreeApi(params);
            if (res.code == 200 && Array.isArray(res.data)) {
                this.ownTreeData = res.data.length > 0 ? res.data[0].commonTreeList : [];
                const targetId = newNodeId || this.selectedNodeId;
                const targetnode = targetId
                    ? this.recurNodeForTarget(this.ownTreeData, targetId)
                    : this.ownTreeData[0];
                this.nodeClick(targetnode);
            }
        },
        // 递归获取当前树节点
        recurNodeForTarget(nodeArr, id) {
            for (let i = 0; i < nodeArr.length; i++) {
                if (nodeArr[i].id == id) {
                    return nodeArr[i];
                } else {
                    if (nodeArr[i].children && nodeArr[i].children.length > 0) {
                        let node = this.recurNodeForTarget(nodeArr[i].children, id);
                        if (node) {
                            return node;
                        }
                    }
                }
            }
        },
        // 新增文件夹
        handleAddOrUpdateFolder(sign, node) {
            this.isAddOrUpdateFolder = true;
            this.$nextTick(() => {
                this.$refs["addOrUpdateFolderRef"].init(
                    sign,
                    node,
                    this.ownTreeData,
                    "account"
                );
            });
        },
        // 新增数据模型
        handleAddModel(node) {
            this.isAddOrUpdateModel = true;
            this.$nextTick(() => {
                this.$refs["addOrUpdateModelRef"].init(undefined, node);
            });
        },
        // 点击树节点，右侧展示详细信息
        async nodeClick(node) {
            if (node == undefined) {
                return;
            }
            this.selectedNodeInfo = node;
            this.currentNodeKey = node.id;
            this.$nextTick(() => {
                this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
            })
            this.$store.commit("modelManageTool/SET_SELECTED_NODE_ID", { moduleName: 'model', id: node.id })
            if (!node.data) return;

            if (node.type == 0) {
                // 点击的文件夹
                this.isFolder = true;
                this.isModel = false;
                this.$store.commit("modelManageTool/SET_EXPANDED_NODE_IDS", { moduleName: 'model', idList: Array.from(new Set([...this.defaultExpandedKeys, node.id])) })
                this.folderForm = node.data;
                this.$refs.folderForm.clearValidate();
            } else {
                // 点击的文件
                this.isFolder = false;
                this.isFile = true;
                this.isModel = true;
                console.log(node.data)
                getBaseVersionList(node.id).then((response) => {
                    this.baseVersionList = response.data
                })
                const res = await getAlgorithmDetailsApi(node.data.refId);
                if (res.code === 200) {
                    this.itemForm = res.data
                    if (!this.itemForm.startupParam) {
                        this.itemForm.startupParam = "{\n    \"参数分组1\": {\n        \"--attr1\": {\n            \"type\": \"str\",\n            \"label\": \"参数1\",\n            \"default\": \"value1\",\n            \"editable\": 1,\n            \"describe\": \"这里是这个参数的描述和备注\"\n        }\n    }\n}"
                    }
                    this.$refs.itemForm.clearValidate();
                } else {
                    this.$message.error(res.msg);
                }
                getPodResourceUsage(node.data.refId).then((response) => {
                    this.podResourceUsage = response.data
                })
            }
        },
        /**
         * 树节点删除事件的回调
         * @param node 被删除的节点
         */
        handleNodeDelete(node) {
            this.$confirm(
                `确定删除${node.type == 0 ? "目录" : "数据"}  ${node.data.name
                } ?`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    customClass: "message-box-style",
                    type: "warning",
                }
            )
                .then(async () => {
                    const response = await deleteTreeApi(node.id, 2);
                    if (response.code == 200) {
                        this.$message.success(
                            this.$toolHandle.getI18nName(
                                this.$zh.setup.responseText,
                                this.$en.setup.responseText,
                                this.$i18n.locale,
                                "success"
                            )
                        );
                        if (node.id == this.currentNodeKey) {
                            this.isFolder = false;
                            this.isModel = false;
                        }
                        this.getList();
                    }
                })
                .catch(() => { });
        },
        /**
         * 树节点复制事件的回调
         * @param node 被复制的节点
         */
        handleCopyFile(node) {
            addModel({
                modelName: node.data.modelName + " Copy",
                modelEnglishName: node.data.modelEnglishName + " Copy",
                modelAlias: node.data.modelAlias + " Copy",
                parentId: node.data.parentId,
                nodeType: node.type, // 0表示文件夹，1表示文件
                categoryLabel: node.data.categoryLabel,
                modelResolution: node.data.modelResolution,
                modelDescription: node.data.modelDescription,
                modelType: node.data.modelType, // 0表示标准模型，1表示代理模型，2表示数字样机
                userId: node.data.userId,
            }).then((response) => {
                if (response.code == 200) {
                    this.$message.success(
                        this.$toolHandle.getI18nName(
                            this.$zh.setup.responseText,
                            this.$en.setup.responseText,
                            this.$i18n.locale,
                            "success"
                        )
                    );
                    this.getList();
                }
            });
        },
        // 移动树节点的顺序
        moveNodeOrder(draggingNode, dropNode, dropType) {
            moveTreeApi({
                movedNodeId: draggingNode.data.id, // 被移动节点的id
                referenceNodeId: dropNode.data.id, // 参照节点的id
                position: dropType == "after" ? 1 : dropType == "before" ? -1 : 0, // 相对位置，before:-1,into:0,after:1
                ancestors: draggingNode.data.data.ancestors, // 祖先
                folderChildrenOrder: {
                    parentId:
                        dropType == "inner" ? dropNode.data.id : dropNode.data.parentId, // 父级id
                    siblingIds:
                        dropType == "inner"
                            ? Array.from(dropNode.childNodes).map((item) => item.data.id)
                            : Array.from(dropNode.parent.childNodes).map(
                                (item) => item.data.id
                            ),
                },
            }).then((response) => {
                if (response.code == 200) {
                    this.$message.success(
                        this.$toolHandle.getI18nName(
                            this.$zh.setup.responseText,
                            this.$en.setup.responseText,
                            this.$i18n.locale,
                            "success"
                        )
                    );
                    this.getList();
                }
            });
        },
        // 点击菜单项触发的事件
        handleMenuClick(menu, node) {
            switch (menu.name) {
                case "新增算法版本":
                    this.handleAddModel(node);
                    break;
                case "新增分类":
                    this.handleAddOrUpdateFolder("add");
                    break;
                case "新增算法":
                    this.handleAddOrUpdateFolder("add", node);
                    break;
                case "编辑":
                    this.handleAddOrUpdateFolder("edit", node);
                    break;
                case "复制":
                    // 文件的复制
                    this.handleCopyFile(node);
                    break;
                case "删除":
                    // 文件夹/文件的删除
                    this.handleNodeDelete(node);
                    break;
            }
        },
    },
};
</script>

<style lang="scss" scoped>
.model-manage {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;

    .mm-panel-wrapper-left {
        width: 300px;
        height: 100%;
        flex-grow: 0;
        flex-shrink: 0;
        display: flex;
        position: relative;
        padding: 0 10px;
    }

    .mm-divider {
        width: 1px;
        height: auto;
        flex-grow: 0;
        position: relative;
        align-self: stretch;
        background-color: var(--ui-border-color-split);
    }

    .mm-panel-wrapper-right {
        width: 256px;
        height: 100%;
        min-width: 0px;
        flex-grow: 1;
        flex-shrink: 1;
        display: flex;
        position: relative;
        overflow: auto;
    }
}

.padding20 {
    padding: 20px;
    width: 100%;
}

// .editor-code {
//     margin: 0;
//     padding: 16px;
//     color: #d4d4d4;
//     font-size: 14px;
//     line-height: 1.5;
//     background-color: #1e1e1e;
//     overflow-x: auto;
//     height: 100%;
// }</style>
